import sqlite3
import os

print("=== 修复test.db数据库 ===")

# 定义test.db数据库路径
db_path = './test.db'
absolute_db_path = os.path.abspath(db_path)

# 检查文件是否存在
if os.path.exists(absolute_db_path):
    print(f"找到test.db数据库文件，路径: {absolute_db_path}")
    print(f"文件大小: {os.path.getsize(absolute_db_path)} bytes")
    
    try:
        # 连接到test.db数据库
        conn = sqlite3.connect(absolute_db_path)
        cursor = conn.cursor()
        
        # 检查users表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users';")
        table_exists = cursor.fetchone()
        
        if table_exists:
            print("✓ users表存在")
            
            # 检查password_history列是否存在
            cursor.execute("PRAGMA table_info(users);")
            columns = cursor.fetchall()
            column_names = [col[1] for col in columns]
            
            print(f"当前列: {column_names}")
            
            if 'password_history' not in column_names:
                print("尝试添加password_history列...")
                try:
                    # 添加password_history列，类型为TEXT
                    cursor.execute("ALTER TABLE users ADD COLUMN password_history TEXT;")
                    conn.commit()
                    print("✓ 成功添加password_history列到test.db的users表")
                    
                    # 验证列是否已添加
                    cursor.execute("PRAGMA table_info(users);")
                    updated_columns = cursor.fetchall()
                    updated_column_names = [col[1] for col in updated_columns]
                    
                    if 'password_history' in updated_column_names:
                        print("✓ 验证成功: password_history列已存在")
                    else:
                        print("❌ 验证失败: password_history列仍不存在")
                    
                except sqlite3.Error as e:
                    print(f"❌ 添加列失败: {e}")
                    conn.rollback()
            else:
                print("✓ password_history列已存在，无需修复")
        else:
            print("❌ users表不存在")
        
        # 关闭连接
        conn.close()
        
    except sqlite3.Error as e:
        print(f"❌ 数据库错误: {e}")
else:
    print(f"❌ 找不到test.db数据库文件: {absolute_db_path}")